<?php

namespace Shared;

/**
 * Description of Config
 *
 * @author nofear
 */

// MUST FIX
class Config {
    private $configFolder;
    private $configs = array();
    private static $_instance = null;
    
    private function __construct() {}
    
    public function getConfigFolder() {
        return $this->configFolder;
    }

    public function setConfigFolder($configFolder) {
        if ( !$configFolder ) {
            throw new \Exception('Config folder not set!');
        }
        
        $configFolder = realpath($configFolder);
        
        if ( $configFolder && is_dir($configFolder) && is_readable($configFolder) ) {
            $this->configs = array();   
            $this->configFolder = $configFolder . DIRECTORY_SEPARATOR;
        } else {
            throw new \Exception('Config directory read error: ' . $configFolder );
        }
        
    }
    
    private function includeConfigFile($path) {
        if ( !$path ) {
            throw new \Exception('config file path missing!');
        }
        $file = realpath($path);

        if ( $file && is_file($file) && is_readable($file) ) {
            $basename = explode('.php', basename($file));
            $this->configs[$basename[0]] = include $file;
        }
    }
    
    public function __get($name) {
        if ( !isset($this->configs[$name]) ) {
            $this->includeConfigFile($this->configFolder . $name . '.php');
        }
        if (array_key_exists($name, $this->configs) ) {
            return $this->configs[$name];
        }
        return null;
    }
    
    public static function getInstance(){
        if ( !self::$_instance ) {
            self::$_instance = new self;
        }
        
        return self::$_instance;
    }
}
